﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Cemit.PolyServer.Game
{
    public class GameServer : PolyServer
    {
        public static GameServer Instance { get; private set; }

        List<GameRoom> games = new List<GameRoom>();
        Stack<int> gamePool = new Stack<int>();
        int gameCount = 0;

        public GameServer()
        {
            Instance = this;
        }

        public GameRoom GetRoom(int roomId)
        {
            if (roomId >= gameCount)
            {
                this.LogWarning("该房间还未被注册！");
                return null;
            }

            return games[roomId];
        }

        /// <summary>(从大厅服务器传入)创建一个房间，返回该房间的ID</summary>
        public int CreateRoom(ICollection<string> playerIds)
        {
            int roomId = -1;

            //判断游戏池中是否有已回收的ID
            lock (gamePool)
            {
                if (gamePool.Count > 0)
                {
                    roomId = gamePool.Pop();
                }
            }

            if (roomId != -1)
            {
                games[roomId] = new GameRoom();
            }
            else
            {
                lock (games)
                {
                    games.Add(new GameRoom());
                    gameCount++;
                    roomId = games.Count;
                }
                roomId--;
            }

            games[roomId].Start(playerIds);
            return roomId;
        }

        
    }
}
